package com.older.wptsb.controller;

import com.older.wptsb.domain.po.HealthAdviceRequest;
import com.older.wptsb.domain.po.HealthData;
import com.older.wptsb.mapper.HealthDataMapper;
import com.older.wptsb.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    @Value("${ai.api.key}")
    private String apiKey;

    @Autowired
    private HealthDataMapper healthDataMapper;

    @PostMapping("/health-advice")
    public Result<String> getHealthAdvice(@RequestBody HealthAdviceRequest request) {
        try {
            // 构建请求到阿里云百炼
            String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "qwen-plus");

            Map<String, Object> input = new HashMap<>();
            String prompt = String.format(
                    "作为一名专业的健康顾问，请根据以下健康数据为老人提供详细的健康建议：\n" +
                            "老人姓名：%s\n心率：%s 次/分\n血氧：%s %%\n血压：%s mmHg\n睡眠质量：%s\n预警等级：%s\n\n" +
                            "请提供具体、实用的建议，包括饮食、运动、生活习惯等方面。输出内容应完整详细，不要截断。",
                    request.getElderName(), request.getHeartRate(), request.getBloodOxygen(),
                    request.getBloodPressure(), request.getSleepQuality(), request.getAlertLevel()
            );
            input.put("prompt", prompt);
            requestBody.put("input", input);

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("max_tokens", 1500); // 增加max_tokens以确保完整输出
            parameters.put("temperature", 0.7);
            requestBody.put("parameters", parameters);

            // 发送请求到阿里云
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                Map<String, Object> output = (Map<String, Object>) responseBody.get("output");
                String advice = (String) output.get("text");
                System.out.println("AI服务返回的健康建议：" + advice);
                return Result.success(advice);
            } else {
                return Result.error("AI服务调用失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("AI服务调用异常：" + e.getMessage());
        }
    }

    // 新增流式传输接口
    @GetMapping("/health-advice-stream/{dataId}")
    public SseEmitter getHealthAdviceStream(@PathVariable Integer dataId) {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        try {
            // 获取健康数据
            HealthData healthData = healthDataMapper.selectById(dataId);
            if (healthData == null) {
                emitter.send(SseEmitter.event().name("error").data("未找到指定的健康数据"));
                emitter.complete();
                return emitter;
            }

            // 异步处理AI请求
            CompletableFuture.runAsync(() -> {
                try {
                    // 构建请求到阿里云百炼
                    String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

                    // 构建请求体
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("model", "qwen-plus");

                    Map<String, Object> input = new HashMap<>();
                    String prompt = String.format(
                            "作为一名专业的健康顾问，请根据以下健康数据为老人提供详细的健康建议：\n" +
                                    "老人姓名：%s\n心率：%s 次/分\n血氧：%s %%\n血压：%s mmHg\n睡眠质量：%s\n预警等级：%s\n\n" +
                                    "请提供具体、实用的建议，包括饮食、运动、生活习惯等方面。输出内容应完整详细，不要截断。",
                            healthData.getElderName(), healthData.getHeartRate(), healthData.getBloodOxygen(),
                            healthData.getBloodPressure(), healthData.getSleepQuality(), healthData.getAlertLevel()
                    );
                    input.put("prompt", prompt);
                    requestBody.put("input", input);

                    Map<String, Object> parameters = new HashMap<>();
                    parameters.put("max_tokens", 1500); // 增加max_tokens以确保完整输出
                    parameters.put("temperature", 0.7);
                    requestBody.put("parameters", parameters);

                    // 发送流式请求到阿里云
                    sendStreamRequest(url, requestBody, emitter);
                } catch (Exception e) {
                    try {
                        emitter.send(SseEmitter.event().name("error").data("处理过程中发生错误: " + e.getMessage()));
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    } finally {
                        emitter.complete();
                    }
                }
            });
        } catch (Exception e) {
            try {
                emitter.send(SseEmitter.event().name("error").data("初始化过程中发生错误: " + e.getMessage()));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            } finally {
                emitter.complete();
            }
        }

        return emitter;
    }

    private void sendStreamRequest(String url, Map<String, Object> requestBody, SseEmitter emitter) {
        try {
            java.net.URL obj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

            // 设置请求头
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setRequestProperty("X-DashScope-SSE", "enable");
            connection.setRequestProperty("Accept", "text/event-stream");
            connection.setDoOutput(true);

            // 发送请求体
            String jsonInputString = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(requestBody);
            try (java.io.OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 处理响应流
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                boolean completed = false;

                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("data:")) {
                        String jsonData = line.substring(5); // 移除 "data:" 前缀
                        // 解析JSON并提取文本
                        try {
                            Map<String, Object> responseMap = new com.fasterxml.jackson.databind.ObjectMapper().readValue(jsonData, Map.class);
                            Map<String, Object> output = (Map<String, Object>) responseMap.get("output");
                            if (output != null) {
                                String text = (String) output.get("text");
                                if (text != null) {
                                    emitter.send(SseEmitter.event().name("data").data(text));
                                }
                            }

                            // 检查是否完成
                            String finishReason = (String) ((Map<String, Object>) responseMap.get("usage")).get("output_tokens");
                            if (finishReason != null) {
                                completed = true;
                            }
                        } catch (Exception e) {
                            // 如果解析失败，发送原始数据
                            emitter.send(SseEmitter.event().name("data").data(jsonData));
                        }
                    }
                }

                // 发送完成信号
                if (completed) {
                    emitter.send(SseEmitter.event().name("complete").data("生成完成"));
                } else {
                    emitter.send(SseEmitter.event().name("complete").data("生成可能未完整完成"));
                }
            } else {
                emitter.send(SseEmitter.event().name("error").data("AI服务调用失败，状态码: " + connection.getResponseCode()));
            }
        } catch (Exception e) {
            try {
                emitter.send(SseEmitter.event().name("error").data("网络请求异常: " + e.getMessage()));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } finally {
            emitter.complete();
        }
    }
}
